//
//  BlogController.m
//  oschina_song
//
//  Created by song on 16/1/25.
//  Copyright © 2016年 song. All rights reserved.
//

#import "BlogController.h"
#import "UIColor+utils.h"
#import "OSCBlogs.h"
#import "BlogsCell.h"
#import "OSCAPI.h"
#import "DetailsViewController.h"

static NSString *kBlogsCellID =@"BLOGCELLID";

@interface BlogController ()

@property(nonatomic , assign)BlogsType type;

@end

@implementation BlogController

- (void)viewDidLoad {
    [super viewDidLoad];
      self.view.backgroundColor = [UIColor colorWithHex:0xCCCCCC];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(id)initWithBlogsType:(BlogsType)type
{
    self = [super init];
    if(self){
       self.objclass = [OSCBlogs class];
        NSString *blogtype  =type ==BlogTypeLatest? @"latest":@"recommend";
        self.generateURL =^NSString* (NSUInteger page)
        {
            return [NSString stringWithFormat:@"%@%@?type=%@&pageIndex=%lu&%@",OSCAPI_PREFIX, OSCAPI_BLOGS_LIST ,blogtype , (unsigned long)page ,OSCAPI_SUFFIX];
        };
        
        
        [self.tableView registerClass:[BlogsCell class] forCellReuseIdentifier:kBlogsCellID];

    }
    return  self;
}

-(NSArray *)parseXML:(ONOXMLDocument *)xml
{
        return [[xml.rootElement firstChildWithTag:@"blogs"] childrenWithTag:@"blog"];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OSCBlogs *blogs = self.objects[indexPath.row];
    
    self.label.font = [UIFont boldSystemFontOfSize:15];
    self.label.text =blogs.title;
    CGFloat height =[self.label sizeThatFits:CGSizeMake(tableView.frame.size.width -16, MAXFLOAT)].height;
    
    self.label.font = [UIFont systemFontOfSize:13];
    self.label.text = blogs.body;
    
    height += [self.label sizeThatFits:CGSizeMake(tableView.frame.size.width -16, MAXFLOAT)].height;
    
    return height + 42;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    BlogsCell *cell =[tableView dequeueReusableCellWithIdentifier:kBlogsCellID forIndexPath:indexPath];
    
    OSCBlogs *blogs = self.objects[indexPath.row];
    
    [cell.titleLable setText:blogs.title];
    [cell.bodyLabel setText:blogs.body];
    [cell.authorLabel setText:blogs.author];
    [cell.timeLabel setText:@"2016年1月23"];
    [cell.commentCount setText:@"23"];
    //    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
    //    cell.selectedBackgroundView.backgroundColor = [UIColor blueColor];
    return cell;

}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    OSCBlogs *blog = self.objects[indexPath.row];
    
    DetailsViewController *dvc = [[DetailsViewController alloc] initWithBlog:blog];
    
    [self.navigationController pushViewController:dvc animated:YES];
    
}

@end
